package javagamecontroller.connection;

import java.io.IOException;
import javagamecontroller.activities.ConnectScreen;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;


/**
 * @author Ben Schwab
 *         This thread runs while attempting to make an outgoing connection
 *         with a device. It runs straight through; the connection either
 *         succeeds or fails.
 */
public class ConnectorThread extends Thread {

    private final BluetoothSocket mySocket;
    private final BluetoothDevice myDevice;
    private final ConnectScreen myConnector;
    private BluetoothMessenger myMessenger;

    public ConnectorThread (BluetoothDevice device, ConnectScreen connector,
                            BluetoothMessenger messenger) {
        myDevice = device;
        myMessenger = messenger;
        BluetoothSocket tmp = null;
        myConnector = connector;
        try {
            tmp = device.createRfcommSocketToServiceRecord(myConnector.getActiveUUID());
        }
        catch (IOException e) {

        }
        mySocket = tmp;
    }

    public void run () {
        myConnector.cancelDiscovery();

        // Make a connection to the BluetoothSocket
        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            mySocket.connect();
        }
        catch (IOException e) {
       
            try {
                mySocket.close();
            }
            catch (IOException e2) {
                Log.e("ConnectorThread", "unable to close() socket during connection failure", e2);
            }
            myMessenger.connectionFailed();
            return;

        }

        myMessenger.startMessengerThread(mySocket, myDevice);

    }

    public void cancel () {
        try {
            Log.e("ConnectorThread", "mySocket was forced closed");
            mySocket.close();
        }
        catch (IOException e) {
            Log.e("ConnectorThread", "close() of connect socket failed", e);
        }
    }

}
